<?php

class Helper_String
{
	static public function compress($long, $short, $target)
	{
		if ($long == $short) return false;
		if (strlen($long) > strlen($short)) return false;
		
		$count = 1;
		while ($count)
		{
			$target = str_replace($long, $short, $target, $count);
		}
		
		return $target;
	}
	
	static public function replace($search, $replace, $subject)
	{
		if (is_array($search) && is_array($replace)
		    && count($search) == count($replace))
		{
			return strtr($subject, array_combine($search, $replace));
		}
		else if (!is_array($search) && is_array($replace))
		{
			$len = strlen($search);
			foreach ($replace as $new)
			{
				$subject = substr_replace($subject,
				                          $new,
				                          strpos($search),
				                          $len);
			}
			return $subject;
		}
		else if (is_array($search) && !is_array($replace))
		{
			return str_replace($search, $replace, $subject);
		}
		
		return false;
	}
	
	static function toArray ($subject)
	{
		if (empty($subject)) return array();
		
		$len = mb_strlen($subject);
		$toArray = array();
		for ($i = 0; $i < $len; $i++)
		{
			$toArray[] = mb_substr($subject, $i, 1);
		}
		
		return $toArray;
	}
	
	static function splitChunk ($subject, $len, $glue)
	{
		if (empty($subject)) return "";
		
		$len = mb_strlen($subject);
		$chunkSplit = "";
		$n = 0;
		for ($i = 0; $i < $len; $i++)
		{
			$char = mb_substr($subject, $i);
			if (++$n < $len) $chunkSplit .= $char;
			else
			{
				$chunkSplit .= $glue . $char;
				$n = 0;
			}
		}
		return $chunkSplit;
	}
	
	static function splitSafe ($subject, $maxlen, $after)
	{
		if (empty($subject)) return array();
		if (!is_array($after)) $after = Helper_String::toArray($after);
		
		$len = mb_strlen($subject);
		$splitSafe = array();
		$tmp = "";
		$safe = "";
		$n = 0;
		for ($i = 0; $i < $len; $i++)
		{
			$char = mb_substr($subject, $i, 1);
			$tmp .= $char;
			if (++$n < $maxlen || $safe == "")
			{
				if (array_search($char, $after) !== FALSE)
				{
					$safe .= $tmp;
					$tmp = "";
				}
			}
			else 
			{
				$splitSafe[] = $safe;
				$safe = "";
				$n = 0;
			}
		}
		
		return $splitSafe;
	}
}